<template>
  <Card size="small" class="share-card">
    <template #extra>
      <Button type="primary" shape="round" @click="newRole()"><PlusOutlined /> 添加</Button>
    </template>
    <Table :rowKey="getRowKey" :columns="columns" :data-source="roles" @resizeColumn="resizeColumn" :scroll="{ x: 500, y: tableHeight }" :pagination="pagerOption" @change="onPaged" size="small" bordered>
      <template #bodyCell="{ column, record }">
        <div class="btn-group" v-if="column.key == 'op'">
          <Button type="primary" @click="onEdit(record)"><EditOutlined /> 编辑</Button>
          <Button type="primary" ghost @click="$router.push({ path: '/rbac/role/users', query: { id: record.Id, name: record.Name } })"><UserOutlined /> 用户管理</Button>
          <Button type="primary" @click="setRights(record)"><ControlOutlined /> 权限设置</Button>
          <Button type="primary" danger @click="onRemove(record)"><DeleteOutlined /> 删除</Button>
        </div>
      </template>
    </Table>
  </Card>
  <Modal v-model:visible="showEditRole" :title="role.Id ? '编辑角色' : '添加角色'" centered :width="600" @ok="saveRole">
    <Form :label-col="{ style: { width: '80px' } }">
      <Form.Item label="编号" v-if="role.Id">
        <Input v-model:value="role.Id" :disabled="true" />
      </Form.Item>
      <Form.Item label="名称">
        <Input v-model:value="role.Name" />
      </Form.Item>
    </Form>
  </Modal>
</template>
<script setup>
  import { useStore } from 'vuex';
  import { useRouter } from 'vue-router';
  import { ref, reactive, computed, inject, onMounted } from 'vue';
  import { Card, Button, Table, Modal, Form, Input } from 'ant-design-vue';
  import { PlusOutlined, UserOutlined, EditOutlined, ControlOutlined, DeleteOutlined } from '@ant-design/icons-vue';

  const $store = useStore();
  const $router = useRouter();

  const $http = inject('$http');
  const $modal = inject('$modal');
  const $message = inject('$message');

  const showEditRole = ref(false);

  const roles = ref([]);

  const role = reactive({});
  const pagerOption = reactive({
    current: 1,
    pageSize: 20,
    defaultPageSize: 20,
    total: 0
  });
  const so = reactive({
    level: '',
    keywords: ''
  });

  const columns = reactive([
    {
      title: '序号',
      width: 30,
      resizable: false,
      align: 'center',
      customRender: ({ index }) => (pagerOption.current - 1) * pagerOption.pageSize + index + 1
    },
    { title: '名称', width: 110, resizable: true, dataIndex: 'Name' },
    { title: '创建时间', width: 120, resizable: true, dataIndex: 'CreatedOn' },
    { key: 'op', fixed: 'right', align: 'center', width: 120 }
  ]);

  const tableHeight = computed(() => {
    return $store.state.area.content.height - 180;
  });

  function getRowKey(record) {
    return 'tr' + record.Id;
  }

  function resizeColumn(w, col) {
    col.width = w;
  }

  function onPaged(pg) {
    let index = 1;

    if (pg && pg.current) {
      index = pg.current;
      pagerOption.pageSize = pg.pageSize;
    }

    let searchObject = {
      pageIndex: index,
      pageSize: pagerOption.pageSize,
      name: so.name
    };

    $http.post('/api/rbac/roles/search', searchObject).then(res => {
      roles.value = res.datas;

      pagerOption.current = index || 1;
      pagerOption.total = res.total;
    });
  }

  function onReset() {
    so.account = '';
    so.userName = '';
  }

  function newRole() {
    role.Id = null;
    role.Name = '';

    showEditRole.value = true;
  }

  function onEdit(item) {
    role.Id = item.Id;
    role.Name = item.Name;

    showEditRole.value = true;
  }

  function saveRole() {
    if (!role.Name) {
      $message.error({ key: 'valid', content: '请输入角色名称！' });

      return;
    }

    if (role.Id) {
      $http.put('/api/rbac/role/update', { id: role.Id, name: role.Name }).then(res => {
        if (res.success) {
          $message.success('更新成功！');

          showEditRole.value = false;
          onPaged();
        } else {
          $message.error({ key: 'valid', content: res.message });
        }
      });

      return;
    }

    $http.post('/api/rbac/role/create', { name: role.Name }).then(res => {
      if (res.success) {
        $message.success('添加成功！');

        showEditRole.value = false;
        onPaged();
      } else {
        $message.error({ key: 'valid', content: res.message });
      }
    });
  }

  function onRemove(item) {
    $modal.confirm({
      title: '警告',
      content: '是否确定删除该用户？',
      onOk: () => {
        $http.delete(`/api/rbac/role/${item.Id}`).then(res => {
          if (res.success) {
            $message.success('删除成功！');

            onPaged();
          } else {
            $message.error({ key: 'delete', content: res.message });
          }
        });
      }
    });
  }

  function setRights(rd) {
    $router.push({ path: '/rbac/role/rights', query: { id: rd.Id, name: rd.Name, type: 'role' } });
  }

  onMounted(() => {
    onPaged();
  });
</script>
